package demo1;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Administrator
 * Date: 2023-07-07
 * Time: 23:45
 */
public class Test {
    class ListNode{
        private int val;
        private ListNode next;

        public ListNode(int val){
            this.val = val;
        }
    }
    public ListNode head;


    public void createList(){
        Test.ListNode node1 = new Test.ListNode(10);
        Test.ListNode node2 = new Test.ListNode(15);
        Test.ListNode node3 = new Test.ListNode(18);
        Test.ListNode node4 = new Test.ListNode(21);
        Test.ListNode node5 = new Test.ListNode(25);


        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        this.head = node1;
    }


    public ListNode removeElements1(ListNode head, int key){
        while (head != null && head.val == key) {
            head = head.next;
        }
        if(head == null){
            return null;
        }
        ListNode cur = head;
        ListNode node = head;
        while (cur != null){
            if(cur.val != key){
                node.next = cur;
                node = cur;
            }
            cur = cur.next;
        }
        return head;
    }

    public ListNode removeElements2(ListNode head, int key){
        while (head != null && head.val == key) {
            head = head.next;
        }
        if(head == null){
            return null;
        }
        ListNode cur = head;
        while (cur.next != null){
            if(cur.next.val == key){
                cur.next = cur.next.next;
            }else{
                cur = cur.next;
            }
        }
        return head;
    }

    public ListNode reverseList() {
        ListNode cur = head;
        ListNode prev = null;

        while (cur != null){
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }

    public ListNode middleNode() {
        if(head == null){
            return null;
        }
        if(head.next == null){
            return head;
        }

        ListNode slow = head;
        ListNode fast = head;

        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    public ListNode FindKthToTail(ListNode head,int k) {
        if(k <= 0 || head == null){
            return null;
        }
        ListNode slow = head;
        ListNode fast = head;
        for(int i = 0;i<k-1;i++){
            fast = fast.next;
            if(fast == null){
                return null;
            }
        }
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next;
        }

        return slow;
    }

}
